<template>
  <div>
    <ContentWrap>
      <!-- table内容 -->
      <vxe-grid
        v-bind="tableOption"
        ref="gridRef"
        v-on="gridEvents"
        border="none"
        :row-class-name="customRowClass"
        min-height="300px"
      >
        <template #toolbar_buttons>
          <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-position="left">
            <el-form-item prop="taskName">
              <el-input
                v-model="queryParams.taskName"
                placeholder="名称"
                clearable
                @keyup.enter="handleQuery"
                class="!w-240px"
              />
            </el-form-item>
            <el-form-item>
              <el-button @click="handleQuery">
                <Icon icon="ep:search" class="mr-5px" />
                搜索
              </el-button>
              <el-button @click="resetQuery">
                <Icon icon="ep:refresh" class="mr-5px" />
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </template>
        <template #toolbar_tools>
          <el-button
            class="mr-15px"
            plain
            circle
            @click="insertRow('create', fasle)"
            v-if="taskTypes != undefined"
          >
            <Icon icon="ep:plus" />
            <!-- 新增任务 -->
          </el-button>
          <el-button
            class="mr-15px"
            plain
            circle
            @click="switchRow()"
            v-if="taskTypes != undefined"
          >
            <Icon icon="ep:switch" />
            <!-- 迁移 -->
          </el-button>
          <el-button class="mr-15px" plain circle @click="exportRow()" placeholder="导出">
            <Icon icon="ep:download" />
            <!-- 导出 -->
          </el-button>
        </template>
        <template #status="{ row }">
          <el-button
            size="small"
            plain
            :type="row.status == 1 ? 'success' : 'warning'"
            v-if="row.status || row.status == 0"
            class="right-btn"
          >
            <Icon icon="ep:clock" class="mr-5px" v-if="row.status == 0" />
            <Icon icon="ep:circle-check" class="mr-5px" v-if="row.status == 1" />
            {{ statusOptions.find((item) => item.value == row.status).label }}
          </el-button>
        </template>
        <template #priority="{ row }">
          <el-button
            size="small"
            plain
            :type="row.priority == 2 ? 'danger' : row.priority == 1 ? 'warning' : 'primary'"
            v-if="row.priority || row.priority == 0"
            class="right-btn1"
          >
            <Icon icon="ep:flag" class="mr-5px" />
            {{ priorityOptions.find((item) => item.value == row.priority).label }}
          </el-button>
        </template>
        <template #action="{ row }">
          <!-- <div v-else> -->
          <vxe-button
            size="mini"
            mode="text"
            status="primary"
            icon="vxe-icon-edit"
            @click="editRow(row)"
            >详情
          </vxe-button>
          <!-- </div> -->
        </template>
        <template #explanation="{ row }">
          <!-- <div v-else> -->
          <vxe-button
            size="mini"
            mode="text"
            status="primary"
            icon="vxe-icon-edit"
            class="custom-button"
            @click="editRow(row)"
            >{{
              row.dt.creator +
              ' ' +
              row.dt.operationType +
              ' ' +
              (row.dt.bizGrade === 1
                ? '任务'
                : row.dt.bizGrade === 2
                  ? '子任务'
                  : row.dt.columnName) +
              ' ' +
              (row.dt.originalData ? row.dt.originalData + ' -> ' : '') +
              row.dt.updateData
            }}
          </vxe-button>
          <!-- </div> -->
        </template>

        <template #urgingaction="{ row }">
          <div v-if="hasEditStatus(row)">
            <vxe-button size="mini" status="primary" @click="updateRowEvent(row)">保存</vxe-button>
            <vxe-button size="mini" @click="cancelRowEvent(row)">取消</vxe-button>
          </div>
          <el-button class="mr-15px" v-else plain circle type="danger" @click="urgingDo(row)">
            <Icon icon="ep:alarm-clock" />
          </el-button>
        </template>
      </vxe-grid>

      <!-- 分页组件 -->
      <Pagination
        v-if="status== 1"
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </ContentWrap>

    <!-- 详情 -->
    <vxe-drawer
      resize
      destroy-on-close
      show-footer
      show-confirm-button
      show-cancel-button
      v-model="showEditPopup"
      :title="selectRow ? '编辑' : '新增'"
      width="100%"
      :loading="drawerLoading"
      :confirm-closable="false"
    >
      <div class="containers">
        <div style="width: calc(60% - 20px)" class="left-form">
          <el-row :gutter="16">
            <el-col :span="24">
              <vxe-form ref="formRef" v-bind="formOptions">
                <template #hobbiesList="{ item }">
                  <el-checkbox-group v-model="formOptions.data.hobbiesList" size="default">
                    <el-checkbox-button
                      v-for="city in item.itemRender.options"
                      :value="city.value"
                      :key="city.value"
                      >{{ city.label }}
                    </el-checkbox-button>
                  </el-checkbox-group>
                </template>
              </vxe-form>
              <el-button v-if="status == 0" type="primary" plain @click="openFileForm">
                <Icon icon="ep:upload" class="mr-5px" />
                上传文件
              </el-button>
              <el-table :data="fileTable">
                <el-table-column prop="fileName" label="文件名称" />
                <el-table-column fixed="right" label="操作">
                  <template #default="scope">
                    <el-button link type="danger" @click="handleDelete(scope.$index)"
                      >删除
                    </el-button>
                    <el-link
                      :href="scope.row.fileUrl"
                      :underline="false"
                      download
                      target="_blank"
                      type="primary"
                    >
                      下载
                    </el-link>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
        </div>
        <div class="middle-line"></div>
        <div class="model-steps" style="width: calc(40% - 20px)">
          <div class="model-step-title">
            <div>动态</div>
            <el-button type="primary" plain @click="exportdongtai()">导出 </el-button>
          </div>
          <el-timeline direction="vertical" :active="1" space="200" class="steps" id="stepsName">
            <el-timeline-item v-for="(item, key) in dynamicRecord" :key="key">
              <template #default>
                <el-card>
                  <div class="titles" v-if="status == 0"
                    >{{ timestampToDate(item.createTime) }}
                    <el-button link type="danger" @click="handleStepDelete(item.id)"
                      >删除
                    </el-button>
                  </div>
                  <div
                    class="descriptions"
                    :class="{ 'descriptions-licheng': item.milestone == true }"
                  >
                    <Icon icon="ep:star" class="mr-5px" />{{
                      item.creator +
                      ' ' +
                      item.operationType +
                      ' ' +
                      (item.bizGrade === 1
                        ? '任务'
                        : item.bizGrade === 2
                          ? '子任务'
                          : item.columnName) +
                      ' ' +
                      (item.originalData ? item.originalData + ' -> ' : '') +
                      item.updateData
                    }}
                  </div>
                  <el-button
                    plain
                    type="success"
                    size="small"
                    @click="confirmeditEvent(item.id, true)"
                    class="licheng-right-btn"
                    v-if="status == 0 && !item.milestone"
                  >
                    <Icon icon="ep:star" class="mr-5px" />
                    设为里程碑
                  </el-button>

                  <el-button
                    plain
                    type="warning"
                    size="small"
                    @click="confirmeditEvent(item.id, false)"
                    class="licheng-right-btn"
                    v-if="status == 0 && item.milestone"
                  >
                    <Icon icon="ep:close" class="mr-5px" />
                    取消里程碑
                  </el-button>
                </el-card>
              </template>
              <template #icon>
                <div class="icons"></div>
              </template>
            </el-timeline-item>
          </el-timeline>
          <div class="form-area" v-if="status == 0">
            <vxe-textarea
              v-model="dynamicExplanation"
              size="medium"
              placeholder="按Ctrl+Entry快速发送"
              @keyup="keyupsave"
              rows="4"
            ></vxe-textarea>
            <div class="fasong-buttons">
              <el-button type="primary" @click="confirmfasongEvent()">发送</el-button>
              <el-button type="success" @click="confirmfasongEvent(true)">
                <Icon icon="ep:star" class="mr-5px" />
                发送为里程碑</el-button
              >
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="foot-buttons" v-if="status == 0">
          <el-button @click="showEditPopup = false">取消</el-button>
          <el-button type="primary" @click="confirmEvent">确定</el-button>
        </div>
        <div class="foot-buttons" v-else>
          <el-button type="primary" @click="changeStaus">更改为未完成</el-button>
        </div>
      </template>
    </vxe-drawer>

    <!-- 表单弹窗：添加/修改 -->
    <TableInfoForm ref="tableInfoFormRef" @success="getList" />

    <!-- 选择文件弹窗：添加/修改 -->
    <FileForm ref="formFileRef" @success="addFileList" />

    <!-- 任务迁移 -->
    <el-dialog title="任务迁移" v-model="switchdialogVisible" width="30%" >
      <el-form
        ref="switchFormRef"
        v-loading="switchformLoading"
        :model="switchFormData"
        :rules="switchFormRules"
        label-width="100px"
      >
        <el-form-item label="任务类型">
          <el-tree-select
            v-model="switchFormData.taskType"
            :data="menuTree"
            :default-expanded-keys="[0]"
            :props="defaultProps"
            check-strictly
            node-key="id"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="switchdialogVisible = false">取 消</el-button>
          <el-button  @click="switchComifre" :loading="switchformLoading" type="primary" >确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { onMounted } from 'vue'
import { ChairmanApi } from '@/api/task/chairman'
import { TableConfigApi } from '@/api/task/tableconfig'
import { DynamicRecordApi } from '@/api/task/dynamicrecord'
import { timestampToDate } from '@/utils/formatTime'
import * as MenuApi from '@/api/system/increase'
import { VxeUI } from 'vxe-table'
import XEUtils from 'xe-utils'
import TableInfoForm from '@/views/task/tableinfo/TableInfoForm.vue'
import {
  defaultData,
  deptUsersTree,
  formItmes,
  formOptions,
  priorityOptions,
  statusOptions,
  tableOption,
  getTaskType
} from './table'
import FileForm from './FileForm.vue'
import { FilesApi } from '@/api/task/files'
import { ElMessageBox } from 'element-plus'
import { ReminderApi } from '@/api/task/reminder'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'

import { defaultProps, handleTree } from '@/utils/tree'
const message = useMessage() // 消息弹窗
import download from '@/utils/download'

const { t } = useI18n()
const { currentRoute } = useRouter()
const taskType = currentRoute.value.meta.query.taskType
const taskTypes = ref(currentRoute.value.meta.query.taskType)
const status = currentRoute.value.meta.query.status ? currentRoute.value.meta.query.status : 0
const gridRef = ref()
const formRef = ref()
const steps = ref()
// 查询条件
const queryParams = ref({ taskType: taskType, status: status,pageNo:1,pageSize:10 })
// 导出loading
const exportLoading = ref(false)
const drawerLoading = ref(false)
//快速输入的动态
const dynamicExplanation = ref('')

const selectRow = ref()
const showEditPopup = ref(false)
//任务id
const taskId = ref(null)
const total = ref(0) // 列表的总页数
// 表格查询
const getList = async () => {
  tableOption.loading = true
  try {
    const data = await ChairmanApi.getChairmanList(queryParams.value)
    tableOption.data = data.list
    total.value = data.total
    tableOption.loading = false
  } catch (err) {
    tableOption.loading = false
  }
}
// 查询功能
const handleQuery = () => {
  getList()
}
// 重置查询
const resetQuery = () => {
  queryParams.value = { taskType: taskType }
  getList()
}
//文件列表
const fileTable = ref([])
//查询文件列表
const addFileList = async (data) => {
  console.log('fileData', data)
  let fileData = {
    taskId: taskId.value,
    taskType: 0, // 任务
    fileName: data.fileName,
    fileUrl: data.fileUrl
  }
  fileTable.value.push(fileData)
}
//删除上传的文件
const handleDelete = (index) => {
  fileTable.value.splice(index, 1)
}
//删除动态
const handleStepDelete = async (id) => {
  ElMessageBox.confirm(t('common.delMessage'), t('common.confirmTitle'), {
    confirmButtonText: t('common.ok'),
    cancelButtonText: t('common.cancel'),
    type: 'warning'
  }).then(async () => {
    await DynamicRecordApi.deleteDynamicRecord(id)
    const dynamicData = await DynamicRecordApi.getDynamicRecordList({
      bizType: 1,
      bizId: taskId.value
    })
    dynamicRecord.value = dynamicData
  })
}
//表信息
const tableInfoFormRef = ref()
//添加字段
const openForm = (type, id) => {
  tableInfoFormRef.value.open(type, 'task_chairman', id)
}

/** 添加/修改操作 */
const formFileRef = ref()
const openFileForm = () => {
  formFileRef.value.open()
}
//删除任务
const deleteRow = (row) => {
  ElMessageBox.confirm(t('common.delMessage'), t('common.confirmTitle'), {
    confirmButtonText: t('common.ok'),
    cancelButtonText: t('common.cancel'),
    type: 'warning'
  }).then(async () => {
    await ChairmanApi.deleteChairman(row.id)
    await getList()
  })
}

// 弹框编辑功能
const gridEvents = {
  cellClick({ row, column }) {
    console.log(`单击行：${row.id} 单击列：${column.title}`)
  },
  cellDblclick({ row, column }) {
    console.log(`双击行：${row.id} 双击列：${column.title}`)
  },
  formSubmit() {
    console.log('form submit')
  },
  formReset() {
    console.log('form reset')
  },
  //右键点击
  menuClick({ menu, row, column }) {
    const $grid = gridRef.value
    if ($grid) {
      switch (menu.code) {
        //置顶
        case 'putUp':
          putUp(row)
          break
        //置底
        case 'putDown':
          putDown(row)
          break
        //查看详情
        case 'detail':
          editRow(row)
          break
        //插入
        // case 'insertRow':
        //   insertRow(row, false)
        //   break
        case 'insertChild':
          insertRow(row, true)
          break
        case 'deleteRow':
          console.log('删除')
          deleteRow(row)
          break
      }
    }
  }
}
//置顶
const putUp = (row) => {
  tableOption.loading = true
  row.sort = 0
  ChairmanApi.putUpChairman(row.id)
    .then((res) => {
      getList()
    })
    .catch(() => {})
    .finally(() => {
      tableOption.loading = false
    })
}
//置底
const putDown = (row) => {
  tableOption.loading = true
  row.sort = 0
  ChairmanApi.putDownChairman(row.id)
    .then((res) => {
      getList()
    })
    .catch(() => {})
    .finally(() => {
      tableOption.loading = false
    })
}
const editRowEvent = (row) => {
  const $grid = gridRef.value
  if ($grid) {
    $grid.setEditRow(row)
  }
}
// 点击表格编辑
const dynamicRecord = ref([])
const editRow = async (row) => {
  selectRow.value = row
  taskId.value = row.id
  formOptions.data = Object.assign(XEUtils.clone(defaultData, true), row)
  //动态查询
  const dynamicData = await DynamicRecordApi.getDynamicRecordList({ bizType: 1, bizId: row.id })
  dynamicRecord.value = dynamicData
  console.log('  dynamicRecord.value', dynamicRecord.value)
  //查询提醒时间
  const queryParams = {
    pageNo: 1,
    pageSize: 10,
    parentId: row.id,
    taskType: 1,
    workType: 2
  }
  const pageRes = await ReminderApi.getChairmanReminderPage(queryParams)
  console.log('pageRes', pageRes)
  if (
    pageRes != null &&
    pageRes != undefined &&
    pageRes.list != null &&
    pageRes.list != undefined &&
    pageRes.list.length > 0
  ) {
    let remind = pageRes.list[0]
    console.log('remind', remind)
    formOptions.data.hobbiesList = JSON.parse(remind.week)
    formOptions.data.time = remind.time
  }
  console.log('dynamicRecord', dynamicRecord.value)
  //查询附件
  const data = await FilesApi.getFilesList({ taskId: row.id })
  fileTable.value = data
  showEditPopup.value = true

  nextTick(() => {
    scorrldown()
  })
}
//催办
const urgingDo = async (row) => {
  ReminderApi.manualReminderChairman({ id: row.id, taskType: 1 }).then(() => {
    VxeUI.modal.message({ content: `催办` + row.taskName + `成功`, status: 'success' })
  })
}
const { wsCache } = useCache()
//插入新数据
const insertRow = (row, child) => {
  selectRow.value = undefined
  fileTable.value = []
  dynamicRecord.value = []
  formOptions.data = {
    ...defaultData,
    parentId: 0
  }
  const userInfo = wsCache.get(CACHE_KEY.USER)
  formOptions.data.publisherId = userInfo.user.deptId + '-' + userInfo.user.id
  if (child) {
    formOptions.data.parentId = row.id
  }
  formOptions.data.taskType =
    Number(taskType) == 0 || Number(taskType) == 99 ? '' : Number(taskType)
  showEditPopup.value = true
}
// 是否显示保存取消按钮
const hasEditStatus = (row) => {
  const $grid = gridRef.value
  if ($grid) {
    return $grid.isEditByRow(row)
  }
}
// 行上面的保存
const updateRowEvent = (row) => {
  const $grid = gridRef.value
  if ($grid) {
    $grid.clearEdit().then(() => {
      tableOption.loading = true
      if (row.publisherId) {
        row.publisherId = row.publisherId.split('-')[1]
      }
      if (row.responsibleId) {
        row.responsibleId = row.responsibleId.split('-')[1]
      }
      ChairmanApi.updateChairman(row)
        .then((res) => {
          tableOption.loading = false
          VxeUI.modal.message({ content: `保存成功`, status: 'success' })
        })
        .catch(() => {
          getList()
        })
        .finally(() => {
          tableOption.loading = false
        })
    })
  }
}
// 取消
const cancelRowEvent = (e) => {
  const $grid = gridRef.value
  if ($grid) {
    $grid.clearEdit()
  }
}
//保存
const confirmEvent = async () => {
  const $form = formRef.value
  if ($form) {
    const errMap = await $form.validate()
    if (!errMap) {
      let data = XEUtils.clone($form.data, true)
      if (data.publisherId) {
        data.publisherId = data.publisherId.split('-')[1]
      }
      if (data.responsibleId) {
        data.responsibleId = data.responsibleId.split('-')[1]
      }
      data.fileList = fileTable.value
      data.milestone = false
      if (data.id) {
        tableOption.loading = true
        ChairmanApi.updateChairman(data)
          .then((res) => {
            getList()
            tableOption.loading = false
            showEditPopup.value = false
            VxeUI.modal.message({ content: '保存成功', status: 'success' })
          })
          .catch(() => {})
          .finally(() => {
            tableOption.loading = false
          })
      } else {
        tableOption.loading = true
        ChairmanApi.createChairman(data)
          .then((res) => {
            getList()
            tableOption.loading = false
            VxeUI.modal.message({ content: '保存成功', status: 'success' })
            showEditPopup.value = false
          })
          .catch(() => {})
          .finally(() => {})
      }
    }
  }
}

const columns = [
  {
    field: 'checkbox',
    minWidth: '10',
    align: 'center',
    fixed: 'left',
    resizable: true,
    type: 'checkbox'
  },
  {
    field: 'seq',
    minWidth: '10',
    align: 'center',
    fixed: 'left',
    resizable: true,
    type: 'seq'
  },
  // { field: 'id', title: 'ID' },
  // { field: 'sn', title: '序号', resizable: true },
  {
    field: 'taskName',
    title: '名称',
    editRender: { name: 'input', enabled: status == 0 },
    treeNode: true,
    minWidth: '120',
    showOverflow: 'ellipsis',
    align: 'center',
    fixed: 'left',
    resizable: true
  },
  {
    field: 'explanation',
    title: '任务进展更新',
    editRender: { name: 'input', enabled: status == 0 },
    minWidth: '200',
    showOverflow: 'ellipsis',
    align: 'center',
    slots: { default: 'explanation' }
  },
  {
    field: 'taskDetail',
    title: '任务详情',
    editRender: { enabled: status == 0 },
    slots: { default: 'action' },
    resizable: true,
    minWidth: '70',
    showOverflow: 'ellipsis',
    align: 'center'
  },
  {
    field: 'status',
    title: '状态',
    filters: statusOptions,
    filterMultiple: false,
    slots: { default: 'status' },
    formatter({ cellValue }) {
      const item = statusOptions.find((item) => item.value === cellValue)
      return item ? `${item.label}` : ''
    },
    minWidth: '70',
    showOverflow: 'ellipsis',
    align: 'center'
  },
  {
    field: 'publisherName',
    title: '任务发布人',
    minWidth: '70',
    showOverflow: 'ellipsis',
    align: 'center'
  },
  {
    field: 'taskStartTime',
    title: '开始时间',
    minWidth: '60',
    editRender: {
      name: 'VxeDatePicker',
      enabled: status == 0,
      props: { type: 'datetime' },
      minWidth: '150'
    },
    showOverflow: 'ellipsis',
    align: 'center',
    formatter: ({ cellValue }) => XEUtils.toDateString(cellValue, 'yyyy-MM-dd')
  },
  {
    field: 'taskEndTime',
    title: '完成时间',
    minWidth: '60',
    editRender: {
      name: 'VxeDatePicker',
      enabled: status == 0,
      props: { type: 'datetime' },
      minWidth: '70'
    },
    showOverflow: 'ellipsis',
    align: 'center',
    formatter: ({ cellValue }) => XEUtils.toDateString(cellValue, 'yyyy-MM-dd')
  },
  {
    field: 'responsibleName',
    title: '责任人',
    minWidth: '60',
    showOverflow: 'ellipsis',
    align: 'center'
  },
  {
    field: 'priority',
    title: '优先级',
    filters: priorityOptions,
    filterMultiple: false,
    minWidth: '60',
    slots: { default: 'priority' },
    formatter({ cellValue }) {
      const item = priorityOptions.find((item) => item.value === cellValue)
      return item ? item.label : ''
    },
    minWidth: '70',
    showOverflow: 'ellipsis',
    align: 'center'
  },
  {
    field: 'urging',
    title: '催办',
    slots: { default: 'urgingaction' },
    resizable: false,
    minWidth: '50',
    showOverflow: 'ellipsis',
    align: 'center',
    fixed: 'right'
  }
  // { field: 'explanation', title: '更新时间' },
  // { field: 'explanation', title: '滞后天数' },
  // { field: 'explanation', title: '滞后说明和下步措施' },
  // { field: 'explanation', title: '催办' },
]
// 设置列
const setColumn = async () => {
  console.log('------setColumn------------')
  const addColumn = await TableConfigApi.getTableConfigByTableName(tableOption.id)
  tableOption.columns = columns
  if (addColumn.columnsConfig) {
    tableOption.columns = [
      ...columns,
      ...addColumn.columnsConfig.map((n) => {
        n['showOverflow'] = 'ellipsis'
        n['align'] = 'center'
        n['minWidth'] = '60'
        return n
      })
    ]
  }
  formOptions.items = formItmes
  formOptions.readonly = status == 1
  const dateRender = {
    field: 'hobbiesList',
    title: '提醒日期选择',
    span: 24,
    slots: { default: 'hobbiesList' },
    itemRender: {
      name: 'VxeRadioGroup',
      props: {
        type: 'button'
      },
      options: [
        { label: '周一', value: '2' },
        { label: '周二', value: '3' },
        { label: '周三', value: '4' },
        { label: '周四', value: '5' },
        { label: '周五', value: '6' },
        { label: '周六', value: '7' },
        { label: '周日', value: '1' }
      ],
      events: {
        // change: (value) => {
        //   if(formRef.value.data.hobbiesList == 8) {
        //     formRef.value.data.time = ''
        //   }
        // },
      }
    }
  }
  const timeRender = {
    field: 'time',
    title: '提醒时间选择',
    span: 12,
    itemRender: {
      name: 'VxeDatePicker',
      props: {
        type: 'time',
        clearable: true // 启用清空按钮
      }
    }
  }
  if (addColumn.formConfig) {
    console.log(addColumn.formConfig)
    formOptions.items = [
      ...formOptions.items,
      ...addColumn.formConfig.map((n) => {
        n.itemRender['props'] = {
          clearable: true
        }
        return n
      })
    ]
  }
  formOptions.items = [...formOptions.items, dateRender, timeRender]
  await getList()
}
const customRowClass = ({ rowIndex }) => {
  // 为奇数行添加自定义类名
  return rowIndex % 2 === 0 ? 'odd-row' : ''
}
let oldEntry = ''
const keyupsave = async (e) => {
  if (oldEntry + e.key == 'ControlEnter' || oldEntry + e.key == 'EnterControl') {
    let obj = {
      id: formRef.value.data.id,
      explanation: dynamicExplanation.value,
      milestone: false
    }
    let insert = false
    await ChairmanApi.updateExplanationChairman(obj)
      .then((res) => {
        insert = true
        tableOption.loading = false
        VxeUI.modal.message({ content: '保存成功', status: 'success' })
        oldEntry = ''
        nextTick(() => {
          setTimeout(() => {
            scorrldown()
          }, 200)
        })
      })
      .catch(() => {})
      .finally(() => {
        dynamicExplanation.value = ''
        tableOption.loading = false
      })
    if (insert) {
      const dynamicData = await DynamicRecordApi.getDynamicRecordList({
        bizType: 1,
        bizId: formRef.value.data.id
      })
      // console.log('dynamicData', dynamicData)
      dynamicRecord.value = dynamicData
      nextTick(() => {
        setTimeout(() => {
          scorrldown()
        }, 200)
      })
    }
    oldEntry = ''
  }
  oldEntry = e.key
}
const scorrldown = () => {
  let stepsdom = document.getElementById('stepsName')
  stepsdom.scrollTop = stepsdom.scrollHeight
}
const exportRow = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ChairmanApi.exportChairman(queryParams.value)
    download.excel(data, '任务日志.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}
const confirmfasongEvent = async (value) => {
  let obj = {
    id: formRef.value.data.id,
    explanation: dynamicExplanation.value,
    milestone: value ? value : false
  }
  let insert = false
  await ChairmanApi.updateExplanationChairman(obj)
    .then((res) => {
      insert = true
      tableOption.loading = false
      VxeUI.modal.message({ content: '保存成功', status: 'success' })
      oldEntry = ''
    })
    .catch(() => {})
    .finally(() => {
      dynamicExplanation.value = ''
      tableOption.loading = false
    })
  if (insert) {
    const dynamicData = await DynamicRecordApi.getDynamicRecordList({
      bizType: 1,
      bizId: formRef.value.data.id
    })

    nextTick(() => {
      setTimeout(() => {
        scorrldown()
      }, 200)
    })
    // console.log('dynamicData', dynamicData)
    dynamicRecord.value = dynamicData
  }
}
const confirmeditEvent = async (id, value) => {
  let obj = {
    id: id,
    milestone: value
  }
  let insert = false
  await ChairmanApi.updateMilestone(obj)
    .then((res) => {
      insert = true
      tableOption.loading = false
      VxeUI.modal.message({ content: '修改成功', status: 'success' })
    })
    .catch(() => {})
    .finally(() => {
      dynamicExplanation.value = ''
      tableOption.loading = false
    })
  if (insert) {
    const dynamicData = await DynamicRecordApi.getDynamicRecordList({
      bizType: 1,
      bizId: formRef.value.data.id
    })

    nextTick(() => {
      setTimeout(() => {
        scorrldown()
      }, 200)
    })
    dynamicRecord.value = dynamicData
  }
}
const exportdongtai = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    console.log({
      bizType: 1,
      bizId: formRef.value.data.id
    })
    const data = await ChairmanApi.exportChairmanExcel({
      bizType: 1,
      bizId: formRef.value.data.id
    })
    download.excel(data, '任务动态.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}
const changeStaus = async () => {
  ElMessageBox.confirm('确认修改为未完成', '修改状态', {
    confirmButtonText: t('common.ok'),
    cancelButtonText: t('common.cancel'),
    type: 'warning'
  })
    .then(async () => {
      tableOption.loading = true

      let dates = XEUtils.clone(formRef.value.data, true)
      if (dates.publisherId) {
        dates.publisherId = dates.publisherId.split('-')[1]
      }
      if (dates.responsibleId) {
        dates.responsibleId = dates.responsibleId.split('-')[1]
      }
      const data = {
        ...dates,
        status: 0
      }
      ChairmanApi.updateChairman(data)
        .then((res) => {
          getList()
          tableOption.loading = false
          showEditPopup.value = false
          VxeUI.modal.message({ content: '保存成功', status: 'success' })
        })
        .catch(() => {})
        .finally(() => {
          tableOption.loading = false
        })
    })
    .catch(() => {})
}

/** 获取下拉框[上级菜单]的数据  */
const menuTree = ref<Tree[]>([]) // 树形结构
const menuTreelist = ref<Tree[]>([]) // 树形结构
const getTree = async () => {
  menuTree.value = []
  const res = await MenuApi.getMenuIncreaseList()
  const lists = res.map((item) => {
    return { disabled: item.type == 1?true:false,...item}
  })
  menuTreelist.value = lists
  let menu: Tree = { id: 0, name: '主类目', children: [] }
  menu.children = handleTree(lists)
  menuTree.value.push(menu)
}
// 任务迁移
const switchdialogVisible = ref(false)
const switchRow = async() => {
  const list = await gridRef.value.getCheckboxRecords()
  if(list.length == 0) {
    VxeUI.modal.message({ content: '请选择要迁移的任务', status: 'warring' })
  } else {
  switchdialogVisible.value = true
  }
}

const switchFormRef = ref()
const switchformLoading = ref(false)
const switchFormData = ref({
  taskType:undefined
})
const switchFormRules = ref({
  taskType: [{ required: true, message: '任务类型不能为空', trigger: 'blur' }]

})
const switchComifre = async() => {
  switchformLoading.value = true
  let obj = {
    taskType: menuTreelist.value.find(n=>{return n.id == switchFormData.value.taskType}).taskType,
    ids: await gridRef.value.getCheckboxRecords().map(n=>{return n.id})
  }
  await ChairmanApi.replacementChairman(obj)
  VxeUI.modal.message({ content: '迁移成功', status: 'success' })
  switchformLoading.value = false
  switchdialogVisible.value = false
  handleQuery()
}
onMounted(() => {
  setColumn()
  getTree()
  deptUsersTree()
  getTaskType()
})
</script>
<style lang="scss" scoped>
.model-steps {
  height: 100%;
  overflow-y: auto;
  margin-left: 20px;
  width: auto;
  position: relative;
  ::v-deep(.el-timeline-item) {
    padding-bottom: 0px;
  }
  .title {
    margin-bottom: 20px;
  }

  .titles {
    color: var(--el-text-color-placeholder);
    font-weight: normal;
  }

  .descriptions {
    color: var(--el-text-color-placeholder);
    font-weight: normal;
    margin-bottom: 15px;
    display: flex;
  }

  .icons {
    width: 10px;
    height: 10px;
    border-radius: 10px;
    background: var(--el-text-color-placeholder);
  }

  .form-area {
    width: calc(100% - 40px);
    position: absolute;
    bottom: 20px;
    border: 1px solid #dcdfe6;
    border-radius: 5px;
    margin-left: 25px;
    ::v-deep(.vxe-textarea--inner) {
      border: none !important;
      margin-bottom: 15px;
    }
    .fasong-buttons {
      display: flex;
      justify-content: flex-end;
      position: absolute;
      bottom: 5px;
      text-align: right;
      width: 100%;
      right: 5px;
    }
  }
  .steps {
    height: calc(100% - 180px);
    overflow-y: auto;
    padding-top: 10px;
  }
}

.containers {
  display: flex;
  align-items: stretch; /* 确保子元素的高度拉伸到父元素的高度 */
  height: 100%;
  overflow: hidden;
  border-bottom: 1px solid #dcdfe6;

  .left-form {
    overflow-y: auto;
    overflow-x: hidden;
  }

  .middle-line {
    width: 1px; /* 竖线宽度 */
    background-color: #dcdfe6; /* 竖线颜色 */
    margin-left: 20px;
  }

  .model-steps {
    flex-grow: 1;
    overflow-y: auto;
    overflow-x: hidden;
  }
}

.search {
  display: flex;
  align-items: center;
}

.foot-buttons {
  display: flex;
  align-items: center;
  justify-content: center;
}

::v-deep(.vxe-drawer--body-default) {
  padding: 0 0.8em;
}

.right-btn {
  width: 80px;
  height: 30px;
}

.right-btn1 {
  width: 100px;
  height: 30px;
}
.licheng-right-btn {
  position: absolute;
  bottom: 5px;
  right: 5px;
}
.model-step-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 40px;
}
.descriptions-licheng {
  color: #67c23a !important;
  align-items: 20px;
}
.custom-button {
  white-space: normal;
}
</style>
